/**
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * Created by zhangmengliang on 2015-12-06 0006.
 * PART1:包含Form的FramDialog公共方法,常用于增加和修改弹出窗口
 * PART2:Bootstrap-table数据表格页面通用方法,常用于数据列表展示页面
 * PART3:通用的Ajax方法
 */

layer.config({
    skin: 'layer-ext-moon',
    extend: [
        'skin/moon/style.css',
        'extend/layer.ext.js'
    ]
});

/**
 * 打开对话框(用于表单提交，如创建、修改)
 * @param options [title,url,width,height,callback]
 */
function openFormDialog(options){
    var defaults = {
        title : "",
        url : "404.html",
        callback : function(){

        }
    };
    var op = $.extend({}, defaults, options);
    var width = getWidth(op.width);
    var height = getHeight(op.height);
    var callback;
    if (null != op.callback && typeof op.callback == 'function') {
        callback = op.callback;
    }
    else {
        callback = function(){};
    }
    layer.open({
        type: 2,
        title: op.title,
        shadeClose: true,
        scrollbar: false,
        shade: 0.8,
        area: [width+'px', height + "px"],
        maxmin: true,
        content: op.url,
        btn: ['提交', '关闭'],
        yes: function(index, layero){//提交
            var iframeWin = window[layero.find('iframe')[0]['name']];
            if(null != iframeWin){
                iframeWin.ajaxSubmitFrom("submitForm", callback);
            }
        },
        cancel: function(index){//关闭

        }
    });
}

/**
 * 打开对话框(操作由对话框中的页面做控制)
 * @param options [title,url,width,height]
 */
function openFrameDialog(options){
    var defaults = {
        title : "",
        url : "404.html"
    };
    var op = $.extend({}, defaults, options);
    var width = getWidth(op.width);
    var height = getHeight(op.height);
    layer.open({
        type: 2,
        title: op.title,
        shadeClose: true,
        scrollbar: false,
        maxmin: true,
        shade: 0.8,
        area: [width+'px', height + "px"],
        content: op.url
    });
}

function getWidth(width){
    if (width == null || width == '') {
        var winWidth = $(window).width();
        if(winWidth < 500){
            width = winWidth - 50;
        }
        else {
            width=800;
        }

    }
    return width;
}

function getHeight(height){
    if (height == null || height == '') {
        height=($(window).height() - 200);
    }
    return height;
}

/**
 * 通用ajax提交form
 * @param formId
 * @param callback
 */
function ajaxSubmitFrom(formId, callback){
    var form = $("#" + formId);
    form.isValid(function(v){
        if (v){
            var index = layer.load(1, {shade: [0.6, '#e7e7e7']});
            var options = {
                success: function (e) {
                    layer.close(index);
                    if (e.code == 200) {
                        if (null != callback && typeof callback == 'function') {
                            callback(e);
                        }
                        var dialogIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(dialogIndex);
                    }
                    else {
                        layer.msg(e.msg);
                    }
                },
                error: function (e) {
                    layer.close(index);
                    layer.msg('加载失败');
                }
            };
            form.ajaxSubmit(options);
        }
    });
    return false;
}

/**
 * 初始化datatable公共方法(bootstrap-table使用)
 * @param options
 */
function initBSTable(options){
    var defaults = {
        tableName : "dataTable",
        classes : "table table-bordered table-hover table-striped",
        ajax : "ajaxRequest",
        search : false,
        sidePagination : "server",
        pagination : "true",
        pageSize : 16,
        pageList : [8, 16, 32, 64]
    };
    var op = $.extend({}, defaults, options);
    $("#" + op.tableName).bootstrapTable(op);
}

/**
 * 初始化BSTable的全选框
 */
function initBSTableChkAll(){
    $('#chkAll').on('ifChecked', function(event){
        $('#dataTable td input[type="checkbox"]').iCheck("check");
    });
    $('#chkAll').on('ifUnchecked', function(event){
        $('#dataTable td input[type="checkbox"]').iCheck("uncheck");
    });
    $('#chkAll').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green'
    });
}

/**
 * 初始化datatable公共方法，带查询参数(bootstrap-table使用)
 * 需要提供function postQueryParams
 */
function initBSTableWithQP(){
    initBSTable({queryParams : "postQueryParams"});
}

/**
 * 销毁datatable公共方法
 * @param tableId 默认为dataTable
 */
function distroyBSTable(tableId){
    if(null == tableId || '' == tableId){
        tableId = "dataTable";
    }
    $("#" + tableId).bootstrapTable('destroy');
}

/**
 * 查询datatable公共方法
 */
function searchBSTable(){
    distroyBSTable();
    initBSTableWithQP();
}

/**
 * 向服务器请求数据(bootstrap-table使用)
 * @param contUrl
 * @param bodyUrl
 * @param parames bootstrap-table提供的参数
 * @param bodyId
 */
function requestBSTableData(contUrl, bodyUrl, parames, bodyId){
    var total = 0;
    var funBody = function(eBody){
        parames.success({
            total : total,
            rows : [{}]
        });
        $("#" + bodyId).html(eBody);
    };
    var funCount = function(eCount){
        if(eCount.code == "200"){
            total = eCount.data.count;
            requestBSTableBody(bodyUrl, parames, funBody);
        }
        else if(eCount.code == "301"){
            window.location.href = window.location.href;
        }
        else{
            layer.msg(eCount.msg);
        }
    };
    requestBSTableCount(contUrl, parames, funCount);
}

/**
 * 获得数据总数(bootstrap-table使用)
 * @param contUrl
 * @param parames bootstrap-table提供的参数
 * @param success
 */
function requestBSTableCount(contUrl, parames, success){
    commmonAjax({
        type : 'post',
        url : contUrl,
        data : parames.data,
        error : function(e){
            layer.msg('请求错误');
        },
        success : success
    });
}

/**
 * 获得数据主体(bootstrap-table使用)
 * @param bodyUrl
 * @param parames
 * @param success
 */
function requestBSTableBody(bodyUrl, parames, success){
    commmonAjax({
        type : 'post',
        dataType : 'html',
        url : bodyUrl,
        data : parames.data,
        error : function(e){
            layer.msg('请求错误');
        },
        success : success
    });
}

/**
 * 获得BSTable被选中的数据列表
 * @returns {Array}
 */
function getBSTableCheckList(){
    var checkedList = new Array();
    $("#dataTable td div.icheckbox_square-green").each(function(){
        if($(this).attr("aria-checked") == 'true'){
            checkedList.push($(this).find("input[type='checkbox']").val());
        }
    });
    return checkedList;
}

//通用的ajax方法
function commmonAjax(options){
    var defaults = {
        type : 'POST',
        cache : false,
        dataType : 'json',
        timeout : 30000,
        loading : true
    };
    var op = $.extend({}, defaults, options);
    var index;
    if(op.loading){
        index = layer.load(1, { shade: [0.6,'#e7e7e7']});
    }
    $.ajax({
        type     : op.type,
        url      : op.url,
        data     : op.data || {},
        cache    : op.cache,
        dataType : op.dataType,
        timeout  : op.timeout,
        error	 : function(e){
            if(op.loading){
                layer.close(index);
            }
            if(typeof op.error == 'function'){
                op.error(e);
            }
        },
        success  : function(e){
            if(op.loading){
                layer.close(index);
            }
            if(typeof op.success == 'function'){
                op.success(e);
            }
        }
    });
}

/**
 * 自适应
 */
function autoFrameDialog(){
    var parentIndex = parent.layer.getFrameIndex(window.name);
    parent.layer.iframeAuto(index);
}

/**
 * 关闭指定的对话框
 */
function closeFrameDialog(){
    var parentIndex = parent.layer.getFrameIndex(window.name);
    parent.layer.close(parentIndex);
}

/**
 * 验证并提交指定Form
 * @param formId
 */
function validSubmitForm(formId){
    $('#' + formId).Validform({
        tiptype : 2,
        ajaxPost : true,
        beforeSubmit : function(form){
            var index = layer.load(0, {shade: false});
            var options = {
                success : function(e){
                    layer.close(index);
                    layer.msg(e.msg);
                },
                error : function(e){
                    layer.close(index);
                    layer.msg('加载失败');
                }
            };
            $(form[0]).ajaxSubmit(options);
            return false;
        }
    });
}

/**
 * 提交表单并刷新
 * @param formId
 */
function validSubmitFormAndRefresh(formId){
    $('#' + formId).Validform({
        tiptype : 2,
        ajaxPost : true,
        beforeSubmit : function(form){
            var index = layer.load(0, {shade: false});
            var options = {
                success : function(e){
                    layer.close(index);
                    if(e.code == 200){
                        window.location.href = window.location.href;
                    }
                    else{
                        layer.msg(e.msg);
                    }
                },
                error : function(e){
                    layer.close(index);
                    layer.msg('加载失败');
                }
            };
            $(form[0]).ajaxSubmit(options);
            return false;
        }
    });
}

/**
 * 提交Form
 * @param formId
 * @returns {boolean}
 */
function submitForm(formId){
    var index = layer.load(0, {shade: false});
    var options = {
        success : function(e){
            layer.close(index);
            layer.msg(e.msg);
        },
        error : function(e){
            layer.close(index);
            layer.msg('加载失败');
        }
    };
    $("#" + formId).ajaxSubmit(options);
    return false;
}

//验证并提交指定Form，然后关闭对话框
function validSubmitFormAndCloseDialog(formId, callback){
    $('#' + formId).Validform({
        tiptype : 2,
        ajaxPost : true,
        beforeSubmit : function(form){
            var index = layer.load(0, {shade: false});
            var options = {
                success : function(e){
                    layer.close(index);
                    if(e.code == 200){
                        if(typeof callback == 'function'){
                            callback(e);
                        }
                        var dialogIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(dialogIndex);
                    }
                    else{
                        layer.msg(e.msg);
                    }
                },
                error : function(e){
                    layer.close(index);
                    layer.msg('加载失败');
                }
            };
            $(form[0]).ajaxSubmit(options);
            return false;
        }
    });
}



function pager(url, skip, total, size){
    var options = {
        url: url,
        skip: skip,
        total : total,
        size : size
    };
    commonPager(options);
}

//分页处理
function commonPager(options){
    var defaults = {
        datacont : 'dataContent',
        cont : 'pager',
        type : 'POST',
        url : '',
        data : {},
        timeout : 30000,
        total : 0,
        size : 10,
        mask : true,
        skip : true
    };
    var op = $.extend({}, defaults, options);
    var total = parseInt(op.total); //总记录数
    var size = parseInt(op.size); //每页显示数
    var pages = Math.floor(total / size);
    if (total % size != 0) {
        pages++;
    }
    laypage({
        cont: op.cont, //容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
        pages: pages, //总页数
        curr: op.curr, //初始化当前页
        skip: op.skip, //是否开启跳页
        skin: 'molv',
        jump: function(e, first){ //触发分页后的回调
            var ajaxOptions = {
                type : op.type,
                dataType : 'html',
                url : op.url,
                data : $.extend({}, {
                    curr : e.curr,
                    size : op.size
                }, op.data),
                error : op.error || function(e){
                    layer.msg('请求错误');
                },
                success : op.success || function(e){
                    $("#" + op.datacont).html(e);
                }
            };
            commmonAjax(ajaxOptions);
        }
    });
}

/*
 * 带Confirm的多数据请求
 * confirm 确认的提示信息
 * idlst id的arraylist
 * ajaxdata 除了idlist还需要发送的数据
 * ajaxurl 请求的目标地址
 */
function multiToRequestWithConfirm(options){
    var defaults = {
        confirm	: "确认批量操作选中的记录？",
        idlst : [],
        datacont : 'dataContent',
        ajaxtype : "POST",
        ajaxurl : "",
        ajaxdata : {}
    };
    var op = $.extend({}, defaults, options);
    var checkedNum = op.idlst.length;
    if(checkedNum == 0) {
        layer.msg("请选择至少一项！");
        return;
    }
    layer.confirm(op.confirm, {
        btn: ['确定','取消'] //按钮
    }, function(index){
        multiToRequest(op);
        layer.close(index);
    }, function(){

    });
}

/*
 * 多数据请求
 * idlst id的arraylist
 * ajaxdata 除了idlist还需要发送的数据
 * ajaxurl 请求的目标地址
 */
function multiToRequest(options){
    var defaults = {
        idlst : [],
        datacont : 'dataContent',
        ajaxtype : "POST",
        ajaxurl : "",
        ajaxdata : {}
    };
    var op = $.extend({}, defaults, options);
    var ajaxOptions = {
        type : op.ajaxtype,
        dataType : 'json',
        url : op.ajaxurl,
        data : $.extend({}, op.ajaxdata, {ids : op.idlst.toString()}),
        error : function(e){
            layer.msg('请求错误');
        },
        success : op.success || function(e){
            $("#" + op.datacont).html(e);
        }
    };
    commmonAjax(ajaxOptions);
}

function getFontCss(treeId, treeNode) {
    return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
}

function changeColor(id,key,value){
    var treeId = id;
    var tree = $.fn.zTree.getZTreeObj(treeId);
    var nodes = tree.transformToArray(tree.getNodes());
    updateNodes(tree, nodes, false);
    if(null != value && value != ""){
        nodes = tree.getNodesByParamFuzzy(key, value);
        if(nodes && nodes.length>0){
            updateNodes(tree, nodes, true);
        }
    }
    tree.expandAll(true);
}
function updateNodes(tree, nodes, isHighLight) {
    for( var i=0; i<nodes.length;  i++) {
        nodes[i].highlight = isHighLight;
        tree.updateNode(nodes[i]);
    }
}
